import { Base64 } from "js-base64";
import { domain } from "@/config";
import { previewFile, uploadFile } from '@/api/file'


export function computeUrl (tenantId, bizId, relativePaths) {
    return `${domain}serv-file/api/2/file/preview/${
        tenantId
      }/dataset/${
        bizId
      }/${
        encodeURIComponent(Base64.encode(relativePaths))
      }`
  }
export function dataURLtoFile(dataurl, filename) {
    //将base64转换为文件
    var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, { type: mime });
}

export async function getJsonFile(__this, bizId, fileName) {
    let info = await __this.$myInfo(__this);
    let userId = info.id;
    let version = __this.$route.query.version
    let encodedRelativePath = encodeURIComponent(Base64.encode(`/.annotation/${version}/${fileName}`))

    let res = await previewFile({
        bizId,
        encodedRelativePath,
        type: 'dataset',
        userId,
        ignore: true
    })
    return res
    // if (fn) {
    //     fn(res)
    // }

    // if (typeof (res.data) == 'object' || typeof (res.data) == 'string') {
    //     fn(res.data)
    // } else {
    //     console.log('没有标注')
    // }
}
export async function writeFile(__this, bizId, template, fileName, fn) {

    let info = await __this.$myInfo(__this);
    let version = __this.$route.query.version
    let filesFile = dataURLtoFile(
        `data:text/json;base64,${Base64.encode(JSON.stringify(template))}`,
        fileName
    );
    let data = new FormData();


    data.append("chunkNumber", 1)
    data.append("totalChunks", 1)
    data.append("repeType", '')
    data.append("filename", fileName)
    data.append("relativePath", `/.annotation/${version}/${fileName}`)
    data.append("userId", info.id)
    data.append("type", 'dataset');
    data.append("bizId", bizId)
    data.append("file", new Blob([filesFile]), fileName);

    await uploadFile(data)
    if (fn) {
        fn()
    }
}
